package com.blacktry.config.schedule;

import com.blacktry.entity.blog.Articles;
import com.blacktry.entity.enums.OprLogConst;
import com.blacktry.service.ArticlesService;
import com.blacktry.service.JobService;
import com.blacktry.utils.RedisUtil;
import com.blacktry.utils.log.OperLog;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;


@Component
public class UpdateBlogView implements Job {

    private static final Logger logger = LoggerFactory.getLogger(UpdateBlogView.class);
    private JobService jobService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ArticlesService articlesService;

    @Override
    @OperLog(operModul = "定时任务-Blog浏览量入库",operType = OprLogConst.UPDATE,operDesc = "Blog浏览量入库")
    public void execute(JobExecutionContext context) {
        logger.info("开始执行问题浏览量入库");
        long start = System.currentTimeMillis();
        // 获取全部的key
        String pattern = "BLOG_ID:*";
        Set<String> keys = redisUtil.getKeys(pattern);
        try {
            for (String key : keys
            ) {
                //获取浏览量
                Long viewCount = redisUtil.size(key);
                // 将key拆分
                String[] split = key.split(":");
                // 根据问题id获取
                Articles articles = articlesService.getById(split[1]);
                // 更改浏览量
                articles.setArticleViews(viewCount.intValue() + articles.getArticleViews());
                articlesService.updateById(articles);
                // 删除key
                this.redisUtil.delete(key);
            }
            long end = System.currentTimeMillis();
            logger.info("问题浏览量入库结束，耗时：{}", end - start);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }
}